package principle.prototype.deepClone;

import java.io.*;

/**
 * @author malguy-wang sir
 * @create ---
 */
public class DeepProtoType implements Serializable,Cloneable {
    public String name;
    public DeepCloneableTarget deepCloneableTarget;//引用类型
    public DeepProtoType() {
        super();
    }
    //深拷贝:方法一 clone方法
    @Override
    protected Object clone() throws CloneNotSupportedException {
        Object deep = null;//deep就是这个类的克隆
        //完成对基本数据类型（属性）和字符串的克隆
        deep = super.clone();//浅拷贝
        //引用类型的属性单独处理
        DeepProtoType deepProtoType = (DeepProtoType) deep;//把deep转为这个类
        deepProtoType.deepCloneableTarget =
                (DeepCloneableTarget) deepCloneableTarget.clone();//深拷贝，把引用对象也拷贝，并且赋给这个类的拷贝
        return deepProtoType;
    }
    //方法二，对象序列化
    public Object deepClone(){
        //创建流对象
        ByteArrayOutputStream bos = null;
        ObjectOutputStream oos = null;
        ByteArrayInputStream bis = null;
        ObjectInputStream ois = null;
        try{
            //序列化
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(this);//把当前类作为流输出
            //反序列化
            bis = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bis);
            DeepProtoType o = (DeepProtoType) ois.readObject();
            return o;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }finally {
            try {
                if(ois!=null) ois.close();
                if(bis!=null) bis.close();
                if(oos!=null) oos.close();
                if(bos!=null) bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
